package com.qilu.careprogram.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.converters.string.StringStringConverter;
import com.qilu.careprogram.excelConfig.CustomCellStyleHandler;
import com.qilu.careprogram.excelConfig.CustomCellWriteHandler;
import com.qilu.careprogram.pojo.vo.PatientInfoReturnVisitListVO;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Description: excel下载工具
 * @CreateTime: 2025-04-17  15:46
 * @Version: 1.0
 */
public class ExcelUtil {

    /**
     * @param response
     * @param fileName         文件名字
     * @param list             回访信息表
     * @param mergeColumns     需要合并的列
     * @param optLastColumnIdx 需要合并的列的
     * @param mergeRowStartIdx 需要合并的列的
     */
    public static void downloadExcel(HttpServletResponse response, String fileName, List<?> list, Class c, int[] mergeColumns, int optLastColumnIdx, int mergeRowStartIdx) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        try {
            System.out.println(c.getSimpleName());
            EasyExcel.write(response.getOutputStream(), c)
                    .sheet("病人信息")
                    .head(c)
                    .registerWriteHandler(new CustomCellWriteHandler(optLastColumnIdx, mergeRowStartIdx, mergeColumns, ((cur, pre) -> {
                        /*
                         * 合并逻辑：住院号相同就合并
                         * */
                        String curHospotalNum = cur.getCell(0).getStringCellValue();
                        String preHospotalNum = pre.getCell(0).getStringCellValue();
                        return curHospotalNum.equals(preHospotalNum);
                    })))
                    .registerWriteHandler(new CustomCellStyleHandler())
                    .automaticMergeHead(true)
                    .doWrite(list);
        } catch (Exception e) {
          System.err.println(e);
          e.printStackTrace();
          throw new IOException(e.getMessage());
        }
    }

}
